package com.ruoyi.system.event;

import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.enums.TaskType;
import com.ruoyi.system.domain.SysWhitePaperSurveyTask;
import com.ruoyi.system.fastgpt.service.FastGptService;
import com.ruoyi.system.fastgpt.vo.FastGptResponse;
import com.ruoyi.system.service.ISysWhitePaperSurveyTaskService;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.compress.utils.Lists;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.transaction.event.TransactionPhase;
import org.springframework.transaction.event.TransactionalEventListener;

import java.util.List;

@Component
public class EventListeners {
    protected final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private FastGptService fastGptService;
    @Autowired
    private ISysWhitePaperSurveyTaskService sysWhitePaperSurveyTaskService;

    // 异步监听器
    @Async
    @TransactionalEventListener(phase = TransactionPhase.AFTER_COMMIT)
    public void handleOrderCreatedAsync(WhitePaperSurveyTaskEvent event) {
        logger.info("进入异步处理调研任务方法");

        List<SysWhitePaperSurveyTask> whitePaperSurveyTaskList = event.getWhitePaperSurveyTaskList();
        List<SysWhitePaperSurveyTask> aiTaskList = Lists.newArrayList();
        for (SysWhitePaperSurveyTask whitePaperSurveyTask:whitePaperSurveyTaskList) {
            if (TaskType.AI.getCode().equals(whitePaperSurveyTask.getTaskType())) {// AI分析
                // 调用FastGPT工具，得到调研分析结果
                FastGptResponse fastGptResponse = fastGptService.sendMessage(whitePaperSurveyTask.getInstructionWorkflow(),null);

                // 解析fastGpt的回复内容
                List<FastGptResponse.ChatChoice> choices = fastGptResponse.getChoices();
                if (CollectionUtils.isNotEmpty(choices)) {
                    String responseContent = choices.get(0).getMessage().getContent();

                    int beginIndex = responseContent.indexOf("{");
                    if (beginIndex >= 0) {
                        int endIndex = responseContent.indexOf("}");
                        // 转为JSON类型
                        JSONObject contentJson = JSONObject.parse(responseContent.substring(beginIndex, endIndex + 1));

                        // 调研结果
                        List<String> surveyResultList = Lists.newArrayList();
                        surveyResultList.add(contentJson.getString("内容"));
                        whitePaperSurveyTask.setSurveyResultTitle(contentJson.getString("标题"));
                        whitePaperSurveyTask.setSurveyResultList(surveyResultList);
                    }
                }

                aiTaskList.add(whitePaperSurveyTask);
            } else if (TaskType.WEBSITE.getCode().equals(whitePaperSurveyTask.getTaskType())) {//网站爬虫
                // 网站爬虫任务通过定时任务自动轮询
            }
        }

        // 更新白皮书调研任务状态为“已完成”，并将结果保存至白皮书调研结果表中
        sysWhitePaperSurveyTaskService.updateSurveyTaskStatus(aiTaskList);

        logger.info("异步处理调研任务方法已结束");
    }

}
